# encoding: utf-8
import hashlib
import json
import platform
import uuid
from datetime import datetime, timedelta


def get_hardware_id():
    """获取设备硬件指纹（包含MAC、CPU、主板信息）"""
    # 获取MAC地址
    mac = uuid.getnode()

    # 初始化硬件信息
    cpu_info = "UNKNOWN_CPU"
    board_info = "UNKNOWN_BOARD"

    # Windows系统
    if platform.system() == "Windows":
        try:
            import wmi
            c = wmi.WMI()
            # 获取CPU信息
            cpu_info = c.Win32_Processor()[0].ProcessorId
            # 获取主板信息
            board_info = c.Win32_BaseBoard()[0].SerialNumber
        except:
            pass

    # Linux系统
    elif platform.system() == "Linux":
        try:
            # 获取CPU信息
            with open('/proc/cpuinfo', 'r') as f:
                for line in f:
                    if line.strip() and 'serial' in line.lower():
                        cpu_info = line.split(':')[1].strip()
                        break
            # 获取主板信息
            with open('/sys/class/dmi/id/board_serial', 'r') as f:
                board_info = f.read().strip()
        except:
            pass

    # Mac系统
    elif platform.system() == "Darwin":
        try:
            import subprocess
            # 获取CPU信息
            cpu_info = subprocess.check_output(
                "sysctl -n machdep.cpu.brand_string",
                shell=True
            ).decode().strip()
            # 获取主板信息
            board_info = subprocess.check_output(
                "ioreg -l | grep IOPlatformSerialNumber",
                shell=True
            ).decode().split('=')[-1].strip().strip('"')
        except:
            pass

    # 组合硬件信息
    hardware_str = f"{mac}-{cpu_info}-{board_info}"
    return hashlib.sha256(hardware_str.encode()).hexdigest()


def generate_license(hardware_id, days=365, lic_file="license.lic"):
    """
    生成授权文件
    :param hardware_id: 硬件指纹
    :param days: 授权天数
    :param output_file: 授权文件输出路径
    """
    expire_date = (datetime.now() + timedelta(days=days)).strftime("%Y-%m-%d")
    license_data = {
        "hardware_id": hardware_id,
        "expire_date": expire_date,
        "signature": hashlib.sha256(
            f"{hardware_id}{expire_date}SECURE_KEY_{platform.node()}".encode()
        ).hexdigest()  # 更复杂的签名密钥
    }
    # lic_file = get_file_path()
    with open(lic_file, "w") as f:
        json.dump(license_data, f)

    print(f"授权文件已生成: {lic_file}")
    print(f"硬件指纹: {hardware_id}")
    print(f"到期日期: {expire_date}")


def validate_license(license_file="license.lic"):
    """
    验证授权文件
    :param license_file: 授权文件路径
    :return: (bool, str) 验证结果和消息
    """
    try:
        with open(license_file, "r") as f:
            license_data = json.load(f)
    except FileNotFoundError:
        return False, "授权文件不存在"
    except json.JSONDecodeError:
        return False, "授权文件格式错误"

    # 验证硬件ID
    current_hardware = get_hardware_id()
    if license_data["hardware_id"] != current_hardware:
        return False, "硬件不匹配（可能更换了主板或CPU）"

    # 验证签名
    expected_signature = hashlib.sha256(
        f"{license_data['hardware_id']}{license_data['expire_date']}SECURE_KEY_{platform.node()}".encode()
    ).hexdigest()

    if license_data["signature"] != expected_signature:
        return False, "授权签名无效"

    # 验证有效期
    expire_date = datetime.strptime(license_data["expire_date"], "%Y-%m-%d")
    if datetime.now() > expire_date:
        return False, "授权已过期"

    return True, "授权验证通过"


def show_hardware_info():
    """显示当前硬件信息（用于调试）"""
    mac = uuid.getnode()
    print(f"MAC地址: {mac}")
    print(f"系统类型: {platform.system()}")
    print(f"计算机名称: {platform.node()}")
    print(f"硬件指纹: {get_hardware_id()}")


def checkCode():
    # 客户端启动时验证授权文件
    result, message = validate_license()
    print(result)
    print(message)
    if result:
        print("授权成功")
        return True
    else:
        print("本机器未授权，请查看弹窗提示")
        import tkinter as tk
        import tkinter.ttk as ttk

        root = tk.Tk()
        root.title('提示')
        root.geometry('500x300')

        # 创建标签组件
        label = tk.Label(root, text="请复制该机器码联系管理员授权", font=("Arial", 20))
        label.pack()

        # 客户端生成设备指纹
        hardware_id = get_hardware_id()
        # 创建标签和复制按钮
        label_text = hardware_id

        label = ttk.Label(root, text=label_text)
        label.pack(pady=50)
        copy_button = ttk.Button(root, text='复制', command=lambda: copy_to_clipboard(label_text))
        copy_button.pack()

        def copy_to_clipboard(text):
            # 清空剪贴板内容
            root.clipboard_clear()
            # 复制文本到剪贴板
            root.clipboard_append(text)

        root.mainloop()
        return False


# 使用示例
if __name__ == "__main__":
    show_hardware_info()
    # 客户端生成设备指纹
    hardware_id = get_hardware_id()

    # 授权程序 根据设备指纹和授权有效期生成授权文件
    auth_days = 365
    generate_license(hardware_id, days=auth_days)

    # # 客户端启动时验证授权文件
    # result, message = validate_license()
    # print(result)
    # print(message)
    checkCode()